package net.guerlab.mall.seller.print.websocket;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.*;
import javax.websocket.RemoteEndpoint.Basic;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ClientEndpoint
public class SellerClientWebSocket {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SellerClientWebSocket.class);

    private Basic basic;

    private boolean open = false;

    private boolean error = false;

    private final Map<String, BusinessInterface> businessMap = new ConcurrentHashMap<String, BusinessInterface>();

    public boolean isOpen() {
        return open;
    }

    public boolean isError() {
        return error;
    }

    public void registerBusinessModel(String businessName, BusinessInterface business) {
        if (StringUtils.isBlank(businessName)) {
            return;
        }

        if (business == null) {
            return;
        }

        businessMap.put(businessName, business);
    }
    
    public void close() {
        onClose();
    }

    public void sendMessage(String message) {
        if (!open) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        basic = session.getBasicRemote();

        open = true;
    }

    @OnMessage
    public void onMessage(String message) {
        if (StringUtils.isBlank(message)) {
            return;
        }
        
        LOGGER.info("get service send message : {}", message);

        for (Entry<String, BusinessInterface> entry : businessMap.entrySet()) {
            if (entry == null) {
                continue;
            }

            String businessName = entry.getKey();

            if (!message.startsWith(businessName)) {
                continue;
            }

            if (entry.getValue() == null) {
                continue;
            }

            entry.getValue().onMessage(message.substring(businessName.length()));
            return;
        }
    }
    
    @OnClose
    public void onClose() {
        basic = null;
        open = false;
        error = false;
        businessMap.clear();
    }

    @OnError
    public void onError(Throwable t) {
        error = true;
        
        LOGGER.debug(t.getMessage(), t);
    }
}
